package RentCarProject;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.imageio.ImageIO;
import javax.sql.DataSource;
import javax.swing.*;

public class UpdateCarPerformance {
    JFrame frame;
    JLabel idlabel,namelabel,colorlabel,typelabel,statuslabel,rentlabel,renttimelabel,returntimelabel,renterlabel,countlabel,picturelabel;
    JTextField idField,nameField,colorField,typeField,statusField,rentField,renttimelField,returntimeField,renterField,countField;
    MyButton uploadbutton,exitbutton;
    Object carid=0;
    Car car;
    String address=null;

    public void init() throws Exception {
        frame=new JFrame("修改车辆信息");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//        frame.setBounds(500,300,900,530);
        frame.setSize(900, 530);
        frame.setLocationRelativeTo(null);
        frame.setLayout(null);

        picturelabel=new JLabel();
        picturelabel.setBounds(550,70,260,260);
        picturelabel.setIcon(new ImageIcon("src/picture/addpicture.png"));
        picturelabel.setOpaque(false);

        idlabel=new JLabel("车 辆 密 钥：");
        idlabel.setForeground(Color.white);
        idlabel.setFont(new Font("宋体", Font.BOLD,15));
        idlabel.setBounds(25,70,110,30);
        namelabel=new JLabel("车 辆 名 称：");
        namelabel.setForeground(Color.white);
        namelabel.setFont(new Font("宋体", Font.BOLD,15));
        namelabel.setBounds(25,130,110,30);
        colorlabel=new JLabel("  颜   色  ：");
        colorlabel.setForeground(Color.white);
        colorlabel.setFont(new Font("宋体", Font.BOLD,15));
        colorlabel.setBounds(25,190,110,30);
        typelabel=new JLabel("  车   型  ：");
        typelabel.setForeground(Color.white);
        typelabel.setFont(new Font("宋体",Font.BOLD,15));
        typelabel.setBounds(25,250,110,30);
        statuslabel=new JLabel("车 辆 状 态：");
        statuslabel.setForeground(Color.white);
        statuslabel.setFont(new Font("宋体",Font.BOLD,15));
        statuslabel.setBounds(25,310,110,30);
        rentlabel=new JLabel("租金（元/天）：");
        rentlabel.setForeground(Color.white);
        rentlabel.setFont(new Font("宋体",Font.BOLD,15));
        rentlabel.setBounds(275,70,110,30);
        renttimelabel=new JLabel("最后租出时间：");
        renttimelabel.setForeground(Color.white);
        renttimelabel.setFont(new Font("宋体",Font.BOLD,15));
        renttimelabel.setBounds(275,130,110,30);
        returntimelabel=new JLabel("最后还车时间：");
        returntimelabel.setForeground(Color.white);
        returntimelabel.setFont(new Font("宋体",Font.BOLD,15));
        returntimelabel.setBounds(275,190,110,30);
        renterlabel=new JLabel("当前租车用户：");
        renterlabel.setForeground(Color.white);
        renterlabel.setFont(new Font("宋体",Font.BOLD,15));
        renterlabel.setBounds(275,250,110,30);
        countlabel=new JLabel("租 赁 次 数：");
        countlabel.setForeground(Color.white);
        countlabel.setFont(new Font("宋体",Font.BOLD,15));
        countlabel.setBounds(275,310,110,30);

        idField=new JTextField();
        idField.setBounds(135,70,90,30);
        nameField=new JTextField();
        nameField.setBounds(135,130,90,30);
        colorField=new JTextField();
        colorField.setBounds(135,190,90,30);
        typeField=new JTextField();
        typeField.setBounds(135,250,90,30);
        statusField=new JTextField();
        statusField.setBounds(135,310,90,30);
        rentField=new JTextField();
        rentField.setBounds(385,70,90,30);
        renttimelField=new JTextField();
        renttimelField.setBounds(385,130,90,30);
        returntimeField=new JTextField();
        returntimeField.setBounds(385,190,90,30);
        renterField=new JTextField();
        renterField.setBounds(385,250,90,30);
        countField=new JTextField();
        countField.setBounds(385,310,90,30);

        if(carid!=null){
            car=getCarbyid(carid);
            idField.setText(String.valueOf(car.getId()));
            nameField.setText(car.getName());
            colorField.setText(car.getColor());
            typeField.setText(car.getType());
            statusField.setText(String.valueOf(car.getState()));
            rentField.setText(String.valueOf(car.getRent()));
            renttimelField.setText(car.getRenttime());
            returntimeField.setText(car.getReturntime());
            renterField.setText(car.getRenter());
            countField.setText(String.valueOf(car.getCount()));
        }

        uploadbutton=new MyButton("提交更改");
        uploadbutton.setBounds(120,380,100,40);
        uploadbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(idField.getText().isEmpty()||nameField.getText().isEmpty()||colorField.getText().isEmpty()||typeField.getText().isEmpty()||statusField.getText().isEmpty()||rentField.getText().isEmpty()||countField.getText().isEmpty()){
                    JOptionPane.showMessageDialog(null,"请填写完整车辆信息！");
                }else{
                    if(statusField.getText().equals("1")||statusField.getText().equals("0")){
                        try {
                            if(searchCarbyid(idField.getText())){
                                car.setId(Integer.parseInt(idField.getText()));
                                car.setName(nameField.getText());
                                car.setColor(colorField.getText());
                                car.setType(typeField.getText());
                                if(statusField.getText().equals("1")){
                                    car.setState(true);
                                }else{
                                    car.setState(false);
                                }
                                car.setRent(Integer.parseInt(rentField.getText()));
                                car.setRenttime(renttimelField.getText());
                                car.setReturntime(returntimeField.getText());
                                car.setRenter(renterField.getText());
                                car.setCount(Integer.parseInt(countField.getText()));
                                car.setPicture(address);
                                try {
                                    if (updateCarmessage(car)) {
                                        JOptionPane.showMessageDialog(frame, "修改信息成功！");
                                    }
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }else{
                                JOptionPane.showMessageDialog(null,"该车辆编号不存在！");
                            }
                        } catch (Exception ex) {
                            throw new RuntimeException(ex);
                        }
                    }else{
                        JOptionPane.showMessageDialog(null,"车辆状态信息填写0（租出）或1（待租）！");
                    }
                }
            }
        });
        exitbutton=new MyButton("退出更改");
        exitbutton.setBounds(330,380,100,40);
        exitbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
            }
        });


        JLabel label=new JLabel(new ImageIcon("src/picture/manageroperationui.png"));
        label.setBounds(0,0,900,530);
        label.setOpaque(false);
        MyButton browseButton = new MyButton("导入图片");
        browseButton.setBounds(600,360,160,50);
        browseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browseAndUpload();
            }
        });

        frame.add(picturelabel);
        frame.add(idlabel);
        frame.add(namelabel);
        frame.add(colorlabel);
        frame.add(typelabel);
        frame.add(statuslabel);
        frame.add(rentlabel);
        frame.add(renttimelabel);
        frame.add(returntimelabel);
        frame.add(renterlabel);
        frame.add(countlabel);

        frame.add(idField);
        frame.add(nameField);
        frame.add(colorField);
        frame.add(typeField);
        frame.add(statusField);
        frame.add(rentField);
        frame.add(renttimelField);
        frame.add(returntimeField);
        frame.add(renterField);
        frame.add(countField);

        frame.add(uploadbutton);
        frame.add(exitbutton);
        frame.add(browseButton);
        frame.add(label);
        frame.setVisible(true);
    }

    public boolean searchCarbyid(Object id) throws Exception {
        Properties properties=new Properties();
        properties.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(properties);
        Connection connection=dataSource.getConnection();
        String sql="select * from car where id=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setObject(1,id);
        ResultSet resultSet=preparedStatement.executeQuery();
        if(resultSet.next()) {
            resultSet.close();
            preparedStatement.close();
            connection.close();
            return true;
        }else{
            resultSet.close();
            preparedStatement.close();
            connection.close();
            return false;
        }
    }

    public Car getCarbyid(Object id) throws Exception {
        Properties properties=new Properties();
        properties.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(properties);
        Connection connection=dataSource.getConnection();
        String sql="select * from car where id=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setObject(1,id);
        ResultSet resultSet=preparedStatement.executeQuery();
        Car car=new Car();
        if(resultSet.next()){
            car.setId(resultSet.getInt("id"));
            car.setName(resultSet.getString("name"));
            car.setColor(resultSet.getString("color"));
            car.setType(resultSet.getString("type"));
            car.setState(resultSet.getBoolean("status"));
            car.setRent(resultSet.getInt("rent"));
            car.setRenttime(resultSet.getString("renttime"));
            car.setReturntime(resultSet.getString("returntime"));
            car.setRenter(resultSet.getString("renter"));
            car.setCount(resultSet.getInt("count"));
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return car;
    }

    public boolean updateCarmessage(Car car) throws Exception {
        String a="renttime=null";
        String b="returntime=null";
        Properties properties=new Properties();
        properties.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(properties);
        Connection connection=dataSource.getConnection();
        String sql="update car set name=?,color=?,type=?,status=?,rent=?,"+a+","+b+",renter=?,count=?,picture=? where id=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,car.getName());
        preparedStatement.setString(2,car.getColor());
        preparedStatement.setString(3,car.getType());
        preparedStatement.setBoolean(4,car.getState());
        preparedStatement.setInt(5,car.getRent());
        if(car.getRenttime()!=null){
            a="renttime="+car.getRenttime();
        }
        if(car.getReturntime()!=null){
            b="returntime="+car.getReturntime();
        }
        preparedStatement.setString(6,car.getRenter());
        preparedStatement.setInt(7,car.getCount());
        preparedStatement.setString(8,car.getPicture());
        preparedStatement.setInt(9,car.getId());
        int i = preparedStatement.executeUpdate();
        preparedStatement.close();
        connection.close();
        if(i>0){
            return true;
        }else{
            return false;
        }
    }

    private void browseAndUpload() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int result = fileChooser.showOpenDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            address=file.getAbsolutePath();
            System.out.println(address);
            try {//生成略缩图
                BufferedImage originalImage = ImageIO.read(new File(address));
                BufferedImage thumbnailImage = new BufferedImage(260,130,BufferedImage.TYPE_INT_ARGB);
                Graphics2D graphics2D = thumbnailImage.createGraphics();
                graphics2D.drawImage(originalImage.getScaledInstance(260,130,Image.SCALE_SMOOTH), 0,0,null);
                graphics2D.dispose();
                picturelabel.setIcon(new ImageIcon(thumbnailImage));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new UpdateCarPerformance().init();
    }

}